package com.maisonliberte.crawller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.maisonliberte.dao.Dao;
import com.maisonliberte.entity.ImageInfo;
import com.maisonliberte.entity.PriceInfo;
import com.maisonliberte.entity.ProductInfo;
import com.maisonliberte.entity.TableInfo;
import com.maisonliberte.entity.TableOtherInfo;
import com.maisonliberte.enums.ImageSizeEnum;
import com.maisonliberte.util.CalUtil;
import com.maisonliberte.util.HtmlUtil;
import com.maisonliberte.util.HttpUtil;
import com.maisonliberte.util.TranslateUtil;
import com.maisonliberte.util.WeightUtil;

public class BDStoreCrawler extends AbstractCrawler {

	@Override
	public String getNextPage(String data) throws Exception {
		// TODO Auto-generated method stub
		return "";
	}

	@Override
	public void analyzeParsedData(String data) throws Exception {
		
		Document doc = Jsoup.parse(data);
		Elements products = doc.getElementsByClass("cata_list_block_in");
		for(Element em : products){
			this.parsingDataList.add(em.html());
		}
		
	}

	@Override
	public String getDetailUrl(String data) throws Exception {
		try{
			
			Document doc = Jsoup.parse(data);
			Elements cataNames = doc.getElementsByClass("cata_name");
			for(Element e : cataNames){
				Elements as = e.getElementsByTag("a");
				for(Element a : as){
					String url = a.attr("href");
					url = String.format("http://bdstore.jp/%s", url);
					url = url.replace("?pid", "?prid");
					if(Dao.getInstance().isDuplicateProduct(url)){
						System.out.println(String.format("%s is duplicate url", url));
						return null;
					}
					
					if(!url.isEmpty()) return url;
				}
			}
			
			return "";
			
		}catch(Exception ex){
			System.out.print(data);
			System.out.println("getDetailUrl" + ex.getMessage());
			throw ex;
		}
	}

	@Override
	public void analyzerProductDetailInfo(String data, ProductInfo pInfo)
			throws Exception {
		
		String url = "";
		String productName = "";
		String weight = "";
		String spec = "";
		String qty = "";
		int price = 0;
		
		try{
			
			Document doc = Jsoup.parse(data);
			
			TableInfo prodTable = new TableInfo();
			TableOtherInfo prodTableOther = new TableOtherInfo();
			pInfo.setTableInfo(prodTable);
			pInfo.setTableOther(prodTableOther);
			prodTable.setCate(this.category.value());
			prodTable.setForwardFee(true);
			//prodTable.setNumber(Dao.getInstance().getNewProductNumber());
			
			//URL
			String tmp = data.substring(data.indexOf("<link rel=\"alternate\" media=\"handheld\" type=\"text/html\""));
			String tmp_sub = tmp.substring(0, tmp.indexOf("/>") + String.valueOf("/>").length());
			tmp_sub = tmp_sub.substring(tmp_sub.indexOf("href=") + String.valueOf("href=").length());
			tmp_sub = tmp_sub.substring(0, tmp_sub.indexOf("/>"));
			url = tmp_sub.replace("\"", "").trim();
			prodTable.setSourceUrl(url);
			
			//productName
			Elements tmpEl = doc.getElementsByClass("details_name");
			for(Element em : tmpEl){
				productName = tmpEl.text();
			}

			prodTable.setName_jp(productName);
			prodTable.setName(TranslateUtil.translateJpnToKor(productName));
			
			//<p class="det_sent_sub">
			tmpEl = doc.getElementsByClass("det_sent_sub");
			for(Element em : tmpEl){
				tmp = tmpEl.text();
			}
			prodTableOther.setStaff_comment_jpn(tmp);
			prodTableOther.setStaff_comment(TranslateUtil.translateJpnToKor(tmp));
			
			// 在庫
			qty = "6";
			prodTable.setQty(Integer.valueOf(qty));
			
			tmpEl = doc.getElementsByTag("dl");
			for(Element em : tmpEl){

				Elements dts = em.getElementsByTag("dt");
				Elements dds = em.getElementsByTag("dd");
				
				for(int i = 0; i < dts.size(); i++){
					if(dds.size() != dts.size()){
						if(!spec.isEmpty()){
							spec += String.format("<br>■%s", dts.get(i).text());
						}else{
							spec = String.format("■%s", dts.get(i).text());
						}	
					}else{
						if(!spec.isEmpty()){
							spec += String.format("<br>■%s : %s", dts.get(i).text(), dds.get(i).text());
						}else{
							spec = String.format("■%s : %s", dts.get(i).text(), dds.get(i).text());
						}	
					}
				}
			}
			
			prodTable.setExplan_jpn(spec);
			prodTable.setExplan(TranslateUtil.translateJpnToKor(prodTable.getExplan_jpn()));
			
			// 送料
			String localCarriage = "80"; 

			// 価格
			String orgPrice = "";
			tmpEl = doc.getElementsByClass("details_table");
			for(Element em : tmpEl){
				Elements tds = em.getElementsByClass("details_td");
				for(Element e : tds){
					if(e.text().indexOf("円") > -1){
						orgPrice = e.text().replace("円", "").replace("(税込)", "").replace(",", "");
					}
				}
			}
			
			price = 0;
			
			weight = WeightUtil.getWeight(this.category);
			PriceInfo priceInfo = CalUtil.getPrice(Integer.valueOf(orgPrice), Integer.valueOf(localCarriage), Integer.valueOf(weight));
			pInfo.setPriceInfo(priceInfo);
			prodTable.setPrice(priceInfo.Price());
			prodTable.setConsumerPrice(priceInfo.ConPrice());
			prodTable.setCarriage(String.valueOf(priceInfo.getEmsFee()));
			
			// SELECTOR
			boolean isLong = false;
			boolean isFunction = false;
			boolean isDesign = false;
			boolean isEcho = false;
			boolean isTradition = false;
			boolean isRare = false;
			prodTableOther.setS_long(isLong ? 1 : 0);
			prodTableOther.setS_function(isFunction ? 1 : 0);
			prodTableOther.setS_design(isDesign ? 1 : 0);
			prodTableOther.setS_echo(isEcho ? 1 : 0);
			prodTableOther.setS_tradition(isTradition ? 1 : 0);
			prodTableOther.setS_rare(isRare ? 1 : 0);
			prodTableOther.setStaff_id("M99999");
			prodTableOther.setMaker_id("M99999");
			prodTableOther.setBrand_id("M99999");
			
			System.out.println(String.format("product name : %s parsing end", prodTable.getSourceUrl()));
			
		
		}catch(Exception ex){
			System.out.println("[analyzerProductDetailInfo][url] " + url);
			System.out.println("[analyzerProductDetailInfo][weight] " + weight);
			System.out.println("[analyzerProductDetailInfo][spec] " + spec);
			System.out.println("[analyzerProductDetailInfo][qty] " + qty);
			System.out.println("[analyzerProductDetailInfo][price] " + price);
			System.out.println("[analyzerProductDetailInfo]" + ex.getMessage());
			throw ex;
		}
		
		
		
	}

	@Override
	public void analyzerImageInfo(String data, ProductInfo pInfo)
			throws Exception {
try{
			
			Map<ImageSizeEnum, List<ImageInfo>> imageList = new HashMap<ImageSizeEnum, List<ImageInfo>>();
			String tmp = data;
			String tmp_sub = "";
			String mainImg = "";
			String middleImg = "";
			String listImg = "";
			String displayImg = "";
			String smallImg = "";
			List<String> otherImg = new ArrayList<String>();
			List<String> detailImg = new ArrayList<String>();
			
			Document doc = Jsoup.parse(data);
			Elements ems = doc.getElementsByClass("img_t");
			for(Element em : ems){
				Elements imgs = em.getElementsByTag("img");
				for(Element iem : imgs){
					mainImg = iem.attr("src");
				}
			}
			
			Elements emSub = doc.getElementsByClass("img_m");
			for(Element em : emSub){
				Elements imgs = em.getElementsByTag("a");
				for(Element iem : imgs){
					otherImg.add(iem.attr("href"));
				}
			}
			
			String productCode = getProductCode(data);
			// LARGE
			imageList.put(ImageSizeEnum.LARGE_500px, new ArrayList<ImageInfo>());
			ImageInfo imgInfo = new ImageInfo(mainImg);
			imgInfo.setCode(productCode);
			if(!mainImg.trim().isEmpty()){
				imageList.get(ImageSizeEnum.LARGE_500px).add(imgInfo);	
			}
			
			//middle
			imageList.put(ImageSizeEnum.MIDDLE_250px, new ArrayList<ImageInfo>());
			if(!middleImg.isEmpty()){
				ImageInfo middelImgInfo = new ImageInfo(middleImg);
				imgInfo.setCode(productCode);
				imageList.get(ImageSizeEnum.MIDDLE_250px).add(middelImgInfo);
			}
			
			//list
			imageList.put(ImageSizeEnum.LIST_150px, new ArrayList<ImageInfo>());
			if(pInfo.getListImg() != null){
				listImg = pInfo.getListImg(); 
			}
			
			if(!listImg.isEmpty()){
				ImageInfo listImgInfo = new ImageInfo(listImg);
				imgInfo.setCode(productCode);
				imageList.get(ImageSizeEnum.LIST_150px).add(listImgInfo);
			}
			
			//display
			imageList.put(ImageSizeEnum.DISPLAY_120px, new ArrayList<ImageInfo>());
			if(!displayImg.isEmpty()){
				ImageInfo disImgInfo = new ImageInfo(displayImg);
				imgInfo.setCode(productCode);
				imageList.get(ImageSizeEnum.DISPLAY_120px).add(disImgInfo);
			}
			
			//small
			imageList.put(ImageSizeEnum.SMALL_80px, new ArrayList<ImageInfo>());
			if(!displayImg.isEmpty()){
				ImageInfo smallImgInfo = new ImageInfo(smallImg);
				imgInfo.setCode(productCode);
				imageList.get(ImageSizeEnum.SMALL_80px).add(smallImgInfo);
			}
			
			// OTHER OTHER
			imageList.put(ImageSizeEnum.OTHER_IMG, new ArrayList<ImageInfo>());
			for(String src : otherImg){
				ImageInfo otherImgInfo = new ImageInfo(src);
				imgInfo.setCode(productCode);
				imageList.get(ImageSizeEnum.OTHER_IMG).add(otherImgInfo);
			}
			
			// DETAIL
			imageList.put(ImageSizeEnum.DETAIL_IMG, new ArrayList<ImageInfo>());
			for(String src : detailImg){
				ImageInfo detailImgInfo = new ImageInfo(src);
				imgInfo.setCode(productCode);
				imageList.get(ImageSizeEnum.DETAIL_IMG).add(detailImgInfo);
			}
			
			pInfo.setImageList(imageList);

			
		}catch(Exception ex){
			System.out.println("analyzerImageInfo" + ex.getMessage());
			System.out.println(data);
			throw ex;
		}
		
	}

	@Override
	public String requestDetailUrl(String url) throws Exception {
		try{
			//return HttpUtil.httpGet(url, "euc-jp");
			Document doc = Jsoup.connect(url).get();
			return doc.html();
			
		}catch(Exception e){
			System.out.print(e);
			Thread.sleep(1000);
		}
		return null;
	}

	@Override
	protected String getProductCode(String data) {
		//<meta property="og:url" content="http://stylestore.allabout.co.jp/mojo/ProductInfo/sku/HA116-10-5000-A007/" />
		String tmp = data.substring(data.indexOf("<link rel=\"alternate\" media=\"handheld\" type=\"text/html\" href=\""));
		tmp = tmp.substring(0, tmp.indexOf(">") + 1);
		Document doc = Jsoup.parse(tmp);
		Elements ems = doc.getElementsByTag("link");
		for(Element e : ems){
			String url = e.attr("href");
			if(!url.isEmpty())
				return url.replace("http://bdstore.jp/?prid=", "");
		}
		
		return "";
	}

	@Override
	protected String getListImg(String data) {
		//<meta property="og:image" content="http://img10.shop-pro.jp/PA01050/042/product/57104624_th.jpg?20130330230512"/>
		if(data.indexOf("<meta property=\"og:image\"") > -1){
			String tmp = data.substring(data.indexOf("<meta property=\"og:image\""));
			tmp = tmp.substring(0, tmp.indexOf(">") + 1);
			tmp = tmp.substring(tmp.indexOf("content=\"") + String.valueOf("content=\"").length());
			tmp = tmp.substring(0, tmp.indexOf("/>")).replace("\"", "");;
			//tmp = tmp.substring(0, tmp.indexOf("?"));
			//tmp = tmp.replace("\"", "").replace("http://stylestore.jp/item/", "").replace("/", "");
			return tmp.trim();	
		}else{
			return "can not find list image";
		}
	}

	@Override
	public ProductInfo getProductInfo(String data) throws Exception{
		try{
			ProductInfo pInfo = new ProductInfo(); 
			String detailUrl = getDetailUrl(data);
			if(detailUrl != null){
				String detailData = requestDetailUrl(detailUrl);
				pInfo.setListImg(getListImg(detailData));
				analyzerProductDetailInfo(detailData, pInfo);
				analyzerImageInfo(detailData, pInfo);
				if(pInfo.getImageList().get(ImageSizeEnum.LARGE_500px).size() == 0){
					return null;
				}
				return pInfo;
			}
			return null;
			
		}catch(Exception ex){
			throw ex;
		}
	}

}
